package com.financing.wap.web.controller.api;

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import com.financing.wap.dto.*;
import com.financing.wap.service.*;
import com.financing.wap.util.RandomUtils;
import com.financing.wap.vo.*;

import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import net.sf.json.JSONObject;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.common.CommonConstantUtil;
import com.financing.wap.common.CommonConstantUtil.CommonStatus;
import com.financing.wap.common.CommonConstantUtil.UserInfoStatus;
import com.financing.wap.common.Pager;
import com.financing.wap.common.ResultMap;
import com.financing.wap.service.weixin.service.WeixinService;
import com.financing.wap.util.DTOdateSetUtil;
import com.financing.wap.util.DateUtil;
import com.financing.wap.web.controller.BaseController;
/***
 * 用户访问
 *
 */
@Controller("dstUserVisitLogController")
@RequestMapping("/api/dstUserVisitLog")
public class DstUserVisitLogController extends BaseController  { 

	private Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private IDstUserVisitLogService dstUserVisitLogService;
	
	@Autowired
	private IDstUserArticleService dstUserArticleService;

	@Autowired
	private IDstUserSettingService dstUserSettingService;
	
	@Autowired
	private IDstUserInfoService dstUserInfoService;
	
	@Autowired
	private ICommonService commonService;

    @Autowired
    private ICommonDstService commonDstService;
	
	@Autowired
	private IDstArticleService dstArticleService;

    @Autowired
    private IDstUserWeeklyService dstUserWeeklyService;

    @Autowired
    private WeixinService weixinJincsServiceImpl;

	@Autowired
	private IDstIntegralRuleService dstIntegralRuleService;
	
	@Autowired
	protected IDstMemberInfoService dstMemberInfoService;

	@Autowired
	private IDstArticleShareLogService dstArticleShareLogService;
	
	@Autowired
	private IDstUserClientViewService dstUserClientViewService;

	private static final Object obj = new Object();
    
	/***
	 * 我的访客记录列表 
	 * @param request
	 * @param dstUserVisitLog
	 * @param pager
	 * @return
	 */
	@RequestMapping("/listDstUserVisitLog")
	@ResponseBody
	public ResultMap list(HttpServletRequest request, DstUserVisitLogDTO dstUserVisitLog,Pager pager){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("query dstUserVisitLog list begin .......");
			
			 String openid=request.getParameter("openid");
			//参数  默认
			if(StringUtils.isBlank(openid)){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
            String type=request.getParameter("type");
            //参数  默认
            if(StringUtils.isBlank(openid)){
                result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
                result.setStatus(ResultMap.STATUS.FAILE);
                return result;
            }

            type = org.apache.commons.lang.StringUtils.isBlank(type)?"7":type;
            String dateStart = null;
            String dateEnd = null;

            if(org.apache.commons.lang.StringUtils.isBlank(dateStart) ||  org.apache.commons.lang.StringUtils.isBlank(dateEnd)) {
                if (type.equals("7")) {
                    dateEnd = DateUtil.formatDate(new Date(), "yyyy-MM-dd");
                    dateStart = DateUtil.formatDate(DateUtil.addDay(new Date(), -7), "yyyy-MM-dd");
                } else  if (type.equals("30")){
                    dateEnd = DateUtil.formatDate(new Date(), "yyyy-MM-dd");
                    dateStart = DateUtil.formatDate(DateUtil.addDay(new Date(), -30), "yyyy-MM-dd");
                }else{
                    dateEnd = DateUtil.formatDate(new Date(), "yyyy-MM-dd");
                    dateStart = DateUtil.formatDate(DateUtil.addDay(new Date(), -90), "yyyy-MM-dd");
                }
            }

			dstUserVisitLog.setUserOpenid(openid);
			//List<DstUserVisitLogDTO> dstUserVisitLogList = dstUserVisitLogService.queryList(dstUserVisitLog);

			dstUserVisitLog.setBegin(pager.getStartIndex());
			dstUserVisitLog.setPageSize(pager.getPageSize());
            //dstUserVisitLog.setCreateDateStart(dateStart);
            //dstUserVisitLog.setCreateDateEnd(dateEnd);

            //访客记录-按照type 查询，时间分组
			List<String> groupDate = commonService.dstUserVisitLogGroupDate(dstUserVisitLog);
			TreeMap<String,List<DstUserVisitLogVO>> listMap =  new TreeMap<String, List<DstUserVisitLogVO>>();
			for (String date :groupDate){
				listMap.put(date,new ArrayList<DstUserVisitLogVO>());
			}

			int count = commonService.dstUserVisitLogListCount(dstUserVisitLog);

			pager.setTotalCount(count);

			List<DstUserVisitLogVO> dstUserVisitLogList = commonService.dstUserVisitLogList(dstUserVisitLog);

            HashMap<String,CacheUserInfoVO> cacheMap = getCacheObject(openid, dstUserVisitLogList);

            for(DstUserVisitLogVO userVisitLogVO :dstUserVisitLogList){
				userVisitLogVO.setVisitStayDateStr(DateUtil.formatDateTime(userVisitLogVO.getVisitStayDate()));
				userVisitLogVO.setCreateDateStr(DateUtil.formatDate(userVisitLogVO.getCreateDate(),"HH:mm:ss"));
				List<DstUserVisitLogVO> dateList = listMap.get(DateUtil.formatDate(userVisitLogVO.getCreateDate(),"yyyy-MM-dd"));
                //
                String shareUserOpenidPath = userVisitLogVO.getShareUserOpenidPath();
                String shareUserNamePath = userVisitLogVO.getShareUserNamePath();
                if(StringUtils.isNotBlank(shareUserOpenidPath)){
                    List<Map> shareList = new ArrayList<Map>();
                    String[] shareUserOpenidPaths = shareUserOpenidPath.split(",");
                   // String[] shareUserNamePaths = shareUserNamePath.split("@sfa@");

                    int j = 0;
                    for (int i =0;i< shareUserOpenidPaths.length;i++) {
                        String userOpenid = shareUserOpenidPaths[i];
                        if(openid.equals(userOpenid) && i != 0){
                            j = i-1;
                        }
                    }

                    for (int i = j;i< shareUserOpenidPaths.length;i++) {
                        String userOpenid = shareUserOpenidPaths[i];
                       // String name = shareUserNamePaths[i];
                        Map map = new HashMap();

                        map.put("openid",userOpenid);
                        if(openid.equals(userOpenid)){
                            map.put("name","我");
                        }else{
                            map.put("name",cacheMap.containsKey(userOpenid)?cacheMap.get(userOpenid).getUserName():"姓名");
                        }
                        shareList.add(map);
                    }
                    userVisitLogVO.setSharePath(shareList);
                }else{
                    List<Map> shareList = new ArrayList<Map>();
                    Map map = new HashMap();
                    map.put("openid",openid);
                    map.put("name","我");
                    shareList.add(map);

                    if(StringUtils.isNotBlank(userVisitLogVO.getShareUserOpenid())) {
                        Map sharMap = new HashMap();
                        sharMap.put("openid", userVisitLogVO.getShareUserOpenid());
                        sharMap.put("name", userVisitLogVO.getShareUserName());
                        shareList.add(sharMap);
                    }

                    userVisitLogVO.setSharePath(shareList);
                }
				dateList.add(userVisitLogVO);
			}

			//统计分享-iconlist
            Map<String,String> papMap = new HashMap<String, String>();
            papMap.put("userOpenid",openid);
            papMap.put("createDateStart",dateStart);
            papMap.put("createDateEnd",dateEnd);

            List< Map<String,Object> > iconListQuery = commonService.listDstUserVisitLogIcon(papMap);
            Map<String,List<String>> map =  new HashMap<String, List<String>>();
            List<String> viewPeople = new ArrayList<String>();
            List<String> dateCode = new ArrayList<String>();
            List<String> viewCount = new ArrayList<String>();

            int allViewPeople = 0;
            int allViewCount = 0;
            for(Map<String,Object>  iconMap:iconListQuery){
                Long viewPeopleBig = (Long) iconMap.get("viewPeople");
                BigDecimal viewCountBig = (BigDecimal) iconMap.get("viewCount");
                allViewPeople = allViewPeople + Integer.valueOf(viewPeopleBig.toString());
                allViewCount = allViewCount + Integer.valueOf(viewCountBig.toString());
                viewPeople.add(viewPeopleBig.toString());
                dateCode.add(iconMap.get("dateCode").toString());
                viewCount.add(viewCountBig.toString());
            }

            map.put("viewPeople",viewPeople);
            map.put("viewCount",viewCount);
            map.put("dateCode",dateCode);

            //统计-总流量
            DstUserCountInfoVO visitDateLog = commonService.visitDateLog(openid);
            result.setAttribute("allCount", visitDateLog.getAllVist());
			
			result.setAttribute("pager", pager);
            result.setAttribute("iconList", map);
            result.setAttribute("allViewPeople", allViewPeople);
            result.setAttribute("allViewCount", allViewCount);
			result.setAttribute("list", analysisMapDate(listMap));
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("query dstUserVisitLog list end .......");
		}catch(Exception e){
			log.error("query dstUserVisitLog error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}

    private HashMap<String,CacheUserInfoVO> getCacheObject(String openid, List<DstUserVisitLogVO> dstUserVisitLogList) {
        //获取所有的openId\
        StringBuilder cacheObject = new StringBuilder();

        for(DstUserVisitLogVO dstUserVisitLogVO :dstUserVisitLogList){

            if(StringUtils.isBlank(dstUserVisitLogVO.getShareUserOpenidPath())){
                cacheObject.append("'");
                cacheObject.append(dstUserVisitLogVO.getVisitUserOpenid());
                cacheObject.append("'");
                cacheObject.append(",");
            }else {

                String[] cacheoOpenids = dstUserVisitLogVO.getShareUserOpenidPath().split(",");
                for (String cacheoOpenid : cacheoOpenids) {
                    cacheObject.append("'");
                    cacheObject.append(cacheoOpenid);
                    cacheObject.append("'");
                    cacheObject.append(",");
                }
            }
        }

        String  openidPathCache =  cacheObject.toString();
        HashMap map = new HashMap();
        map.put("openidPath",openidPathCache.substring(0,openidPathCache.lastIndexOf(",")));
        map.put("openid",openid);

        //获取最新用户信息
        HashMap<String,CacheUserInfoVO> cacheMap = new HashMap<String,CacheUserInfoVO>();
        List<CacheUserInfoVO> cacheList = commonDstService.cacheUserInfo(map);
        for( CacheUserInfoVO bean :cacheList){
            cacheMap.put(bean.getOpenid(),bean);
        }
        return cacheMap;
    }

    private List<Map<String ,Object>> analysisMapDate(TreeMap<String,List<DstUserVisitLogVO>> listMap) {
		List<Map<String ,Object>> analysisList =  new ArrayList<Map<String, Object>>();
		NavigableMap navigableMap  = listMap.descendingMap();
		Iterator<Map.Entry<String, List<DstUserVisitLogVO>>> it = navigableMap.entrySet().iterator();
	     while (it.hasNext()) {
			 Map.Entry<String, List<DstUserVisitLogVO>> entry = it.next();
			 Map<String ,Object> parMap = new HashMap<String ,Object>();

			 parMap.put("date",DateUtil.analysisDateOne(entry.getKey()));
			 parMap.put("list",navigableMap.get(entry.getKey()));
			 analysisList.add(parMap);
	     }
	     return analysisList;
	}

    /***
     * 我的访客列表
     * @param request
     * @param dstUserVisitVO
     * @param pager
     * @return
     */
    @RequestMapping("/listDstUserVisit")
    @ResponseBody
    public ResultMap listDstUserVisit(HttpServletRequest request, DstUserVisitVO dstUserVisitVO, Pager pager){
        ResultMap result = new ResultMap();

        try{
            logger.info("query listDstUserVisit list begin .......");

            String openid=request.getParameter("openid");

            //参数  默认
            if(StringUtils.isBlank(openid)){
                result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
                result.setStatus(ResultMap.STATUS.FAILE);
                return result;
            }

            dstUserVisitVO.setOpenid(openid);
/*            dstUserVisitVO.setOrderKey("c.visitCount");
            dstUserVisitVO.setOrderValue("desc"); //asc*/
            if(StringUtils.isBlank(dstUserVisitVO.getOrderValue())){
                dstUserVisitVO.setOrderKey("c.createDate");
                dstUserVisitVO.setOrderValue("desc");
            }
            List<DstUserVisitVO> dstUserVisitLogList = commonDstService.dstUserVisitList(dstUserVisitVO);
            for (DstUserVisitVO userVisitVO :dstUserVisitLogList){
                userVisitVO.setSumStayDateStr(DateUtil.formatDateTime(userVisitVO.getSumStayDate()));
                userVisitVO.setCreateDateFormat(DateUtil.formatDateCustom(userVisitVO.getCreateDate()));
                if(StringUtils.isNotBlank(userVisitVO.getUserClientName())){
                    userVisitVO.setUserName(userVisitVO.getUserClientName());
                }else{
                    if(StringUtils.isNotBlank(userVisitVO.getUserNickName())){
                        userVisitVO.setUserName(userVisitVO.getUserNickName());
                    }
                }
            }

            result.setAttribute("list", dstUserVisitLogList);
            result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
            result.setStatus(ResultMap.STATUS.SUCCESS);

            logger.info("query listDstUserVisit list end .......");
        }catch(Exception e){
            log.error("query listDstUserVisit error!",e);
            result.setStatus(ResultMap.STATUS.ERROR);
            result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
        }

        return result;
    }

    /***
     * 我的客户访客记录列表
     * @param request
     * @param dstUserVisitLog
     * @param pager
     * @return
     */
    @RequestMapping("/customerUserVisitLog")
    @ResponseBody
    public ResultMap customerUserVisitLog(HttpServletRequest request, DstUserVisitLogDTO dstUserVisitLog, Pager pager){
        ResultMap result = new ResultMap();

        try{
            logger.info("query customerUserVisitLog list begin .......");

            String openid = request.getParameter("openid");
            String visitUserOpenid = request.getParameter("visitUserOpenid");

            //参数  默认
            if(StringUtils.isBlank(openid) || StringUtils.isBlank(visitUserOpenid)){
                result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
                result.setStatus(ResultMap.STATUS.FAILE);
                return result;
            }

            //访客记录-按照type 查询，时间分组
            dstUserVisitLog.setUserOpenid(openid);
            dstUserVisitLog.setVisitUserOpenid(visitUserOpenid);
            List<String> groupDate = commonService.dstUserVisitLogGroupDate(dstUserVisitLog);
            TreeMap<String,List<DstUserVisitLogVO>> listMap =  new TreeMap<String, List<DstUserVisitLogVO>>();

            for (String date :groupDate){
                listMap.put(date,new ArrayList<DstUserVisitLogVO>());
            }

            //获取所有文章的链路
            List<DstUserVisitLogVO> dstUserVisitLogList = commonDstService.customerUserVisitLog(dstUserVisitLog);
            Map<String,List<String>> atlasMap = new HashMap<String, List<String>>();
            List<String> openidPath = new ArrayList<String>();
            List<String> namePath = new ArrayList<String>();
            List<String> headimgPath = new ArrayList<String>();
            StringBuilder cacheObject = new StringBuilder();
            for(DstUserVisitLogVO userVisitLogVO :dstUserVisitLogList){
                userVisitLogVO.setVisitStayDateStr(DateUtil.formatDateTime(userVisitLogVO.getVisitStayDate()));
                userVisitLogVO.setCreateDateStr(DateUtil.formatDate(userVisitLogVO.getCreateDate(),"HH:mm"));
                List<DstUserVisitLogVO> dateList = listMap.get(DateUtil.formatDate(userVisitLogVO.getCreateDate(),"yyyy-MM-dd"));
                dateList.add(userVisitLogVO);

                //判断
                if("1".equals( userVisitLogVO.getShareType())){
                    userVisitLogVO.setShareType("查看你分享给好友的文章");
                }else if("2".equals( userVisitLogVO.getShareType())){
                    userVisitLogVO.setShareType("查看你转发到朋友圈的文章");
                }

                //链路添加+访问人
                if(StringUtils.isNotBlank(userVisitLogVO.getShareUserOpenidPath())){
                    openidPath.add(userVisitLogVO.getShareUserOpenidPath()+","+visitUserOpenid);
                    namePath.add(userVisitLogVO.getShareUserNamePath()+"@sfa@"+userVisitLogVO.getVisitUserName());
                    headimgPath.add(userVisitLogVO.getShareUserHeadImageurlPath()+"@sfa@"+userVisitLogVO.getVisitUserHeadImageurl());
                }else{
                    //如果链路是空，为顶级链路(自己+访客人)，拼接链路
                    //获取自己信息
                    DstUserInfoDTO dstUserInfo = new DstUserInfoDTO();
                    dstUserInfo.setUserWechatOpenid(openid);
                    dstUserInfo.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
                    DstUserInfoDTO userinfo = dstUserInfoService
                            .queryListGetFirst(dstUserInfo);
                    if(StringUtils.isNotBlank(userVisitLogVO.getShareUserOpenid())){

                        DstUserInfoDTO shareUserInfo = new DstUserInfoDTO();
                        shareUserInfo.setUserWechatOpenid(userVisitLogVO.getShareUserOpenid());
                        shareUserInfo.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
                        shareUserInfo = dstUserInfoService
                                .queryListGetFirst(shareUserInfo);
                        openidPath.add(userinfo.getUserWechatOpenid() + "," +shareUserInfo.getUserWechatOpenid()+ "," +visitUserOpenid);
                        namePath.add(userinfo.getUserName() + "@sfa@" +shareUserInfo.getUserName()+ "@sfa@" + userVisitLogVO.getVisitUserName());
                        headimgPath.add(userinfo.getUserWechatImage() + "@sfa@" +shareUserInfo.getUserWechatImage()+ "@sfa@" + userVisitLogVO.getVisitUserHeadImageurl());

                    }else {
                        openidPath.add(userinfo.getUserWechatOpenid() + "," + visitUserOpenid);
                        namePath.add(userinfo.getUserName() + "@sfa@" + userVisitLogVO.getVisitUserName());
                        headimgPath.add(userinfo.getUserWechatImage() + "@sfa@" + userVisitLogVO.getVisitUserHeadImageurl());
                    }
                }

            }

            //获取所有的openId
            for(String userOpenid :openidPath){
              String[] cacheoOpenids = userOpenid.split(",");
                for(String cacheoOpenid:cacheoOpenids){
                    cacheObject.append("'");
                    cacheObject.append(cacheoOpenid);
                    cacheObject.append("'");
                    cacheObject.append(",");
                }
            }
            String  openidPathCache =  cacheObject.toString();
            HashMap map = new HashMap();
            map.put("openidPath",openidPathCache.substring(0,openidPathCache.lastIndexOf(",")));
            map.put("openid",openid);

            //获取最新用户信息
            HashMap<String,CacheUserInfoVO> cacheMap = new HashMap<String,CacheUserInfoVO>();
            List<CacheUserInfoVO> cacheList = commonDstService.cacheUserInfo(map);
            for( CacheUserInfoVO bean :cacheList){
                cacheMap.put(bean.getOpenid(),bean);
            }

            //生成关系图谱
            atlasMap.put("openidPath",openidPath);
            atlasMap.put("namePath",namePath);
            atlasMap.put("headimgPath",headimgPath);
            result.setAttribute("list", analysisMapDate(listMap));

            List<Map<String,Object>> dataList = new ArrayList<Map<String, Object>>();
            Map<String,Object>  dataMap = new HashMap<String,Object>();

            dataMap.put("graph",relationalAtlas(atlasMap,openid,visitUserOpenid,cacheMap));
            dataList.add(dataMap);
            result.setAttribute("data", dataList);
            result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
            result.setStatus(ResultMap.STATUS.SUCCESS);

            logger.info("query customerUserVisitLog list end .......");
        }catch(Exception e){
            log.error("query customerUserVisitLog error!",e);
            result.setStatus(ResultMap.STATUS.ERROR);
            result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
        }

        return result;
    }



    private VisitAtlasVO relationalAtlas(Map<String, List<String>> atlasMap, String startOpenid, String endOpenid,HashMap<String ,CacheUserInfoVO> cacheMap) {

        //图谱 对象属性
        Map<String,Map<String,Object>> objectMap = new HashMap<String, Map<String, Object>>();
        //关系对象属性
        Map<String,String> gxMap = new HashMap<String, String>();
        //图谱 node
        Map<String,String> nodeMap = new HashMap<String, String>();
        //捷径链路
        List<String> shortcutOpenidPathList = new ArrayList<String>();

        List<String> openidPathList = atlasMap.get("openidPath");
        List<String> namePathList = atlasMap.get("namePath");
        List<String> headimgPathList = atlasMap.get("headimgPath");

        //生成用户对象
        //获取捷径链路
        for (int i = 0;i<openidPathList.size();i++){

            String openidPath = openidPathList.get(i);
            String namePath = namePathList.get(i);
            String headimgPath = headimgPathList.get(i);
            String[] openidPaths = openidPath.split(",");
            String[] namePaths = namePath.split("@sfa@");
            String[] headimgPaths = headimgPath.split("@sfa@");

            for(int j = 0;j<openidPaths.length;j++){

                String openid = openidPaths[j];
                if(!objectMap.containsKey(openid)){

                    Map<String,Object> attributeMap= new HashMap<String,Object>();
                    CacheUserInfoVO cacheUserInfoVO = cacheMap.get(openid);
                    attributeMap.put("keyNo",openid);
                    attributeMap.put("name",cacheUserInfoVO==null?namePaths[j]:cacheUserInfoVO.getUserName());
                    attributeMap.put("role","");
                    attributeMap.put("hasImage",true);
                    attributeMap.put("headimg",headimgPaths[j]);
                    objectMap.put(openid,attributeMap);

                }

            }
            shortcutOpenidPathList.add(openidPath.substring(openidPath.lastIndexOf(startOpenid),openidPath.length()));
        }



        //图谱-节点-关系
        VisitAtlasVO  visitAtlas = new VisitAtlasVO();
        List<NodesVO> nodeList = new ArrayList<NodesVO>();
        List<RelationshipsVO> relationshipsList = new ArrayList<RelationshipsVO>();
        String upNode = StringUtils.EMPTY;

        for (String shortcutOpenidPath:shortcutOpenidPathList){

            String[] shortcutOpenids  = shortcutOpenidPath.split(",");

            for (int k = 0; k < shortcutOpenids.length; k++) {
                String openid = shortcutOpenids[k];
                if (k > 0) {
                    //关系对象
                    upNode = shortcutOpenids[k - 1];
                    RelationshipsVO relationships = new RelationshipsVO();
                    relationships.setId(k + RandomUtils.getRandomUtils(6)+"");
                    relationships.setStartNode(upNode);
                    relationships.setEndNode(openid);
                    Map<String,String> map = new HashMap<String, String>();
                    map.put("role","");
                    relationships.setProperties(map);
                    relationships.setType("LEGAL");
                    if(!gxMap.containsKey(upNode+openid)){
                        relationshipsList.add(relationships);
                        gxMap.put(upNode+openid,"");
                    }
                }

                //节点对象
                if(!nodeMap.containsKey(openid)) {
                    NodesVO nodes = new NodesVO();
                    nodes.setId(openid);
                    nodes.setProperties(objectMap.get(openid));
                    nodeList.add(nodes);
                    nodeMap.put(openid,openid);
                }

            }
        }
        visitAtlas.setNodes(nodeList);
        visitAtlas.setRelationships(relationshipsList);

        return visitAtlas;
    }


    /***
	 * 我的访客记录列表-分享
	 * @param request
	 * @param dstUserVisitLog
	 * @param pager
	 * @return
	 */
	@RequestMapping("/listDstUserVisitLogShare")
	@ResponseBody
	public ResultMap listDstUserVisitLogShare(HttpServletRequest request, DstUserVisitLogDTO dstUserVisitLog,Pager pager){
		ResultMap result = new ResultMap();

		try{

			logger.info("query listDstUserVisitLogShare list begin .......");

			String openid=request.getParameter("openid");
			String type=request.getParameter("type");
			//参数  默认
			if(StringUtils.isBlank(openid)){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}

			type = org.apache.commons.lang.StringUtils.isBlank(type)?"7":type;
			String dateStart = null;
			String dateEnd = null;

			if(org.apache.commons.lang.StringUtils.isBlank(dateStart) ||  org.apache.commons.lang.StringUtils.isBlank(dateEnd)) {
				if (type.equals("7")) {
					dateEnd = DateUtil.formatDate(new Date(), "yyyy-MM-dd");
					dateStart = DateUtil.formatDate(DateUtil.addDay(new Date(), -7), "yyyy-MM-dd");
				} else  if (type.equals("30")){
					dateEnd = DateUtil.formatDate(new Date(), "yyyy-MM-dd");
					dateStart = DateUtil.formatDate(DateUtil.addDay(new Date(), -30), "yyyy-MM-dd");
				}else{
					dateEnd = DateUtil.formatDate(new Date(), "yyyy-MM-dd");
					dateStart = DateUtil.formatDate(DateUtil.addDay(new Date(), -90), "yyyy-MM-dd");
				}
			}

			Map<String,String> papMap = new HashMap<String, String>();
			papMap.put("userOpenid",openid);
			papMap.put("today","today");
			List< Map<String,String> > todayList  = commonService.listDstUserVisitLogShare(papMap);
			papMap.remove("today");
			papMap.put("viewCount","viewCount");
			List< Map<String,String> > viewList  = commonService.listDstUserVisitLogShare(papMap);
			papMap.remove("viewCount");
			papMap.put("forwardCount","forwardCount");
			List< Map<String,String> > forwardList  = commonService.listDstUserVisitLogShare(papMap);
			papMap.put("userOpenid",openid);
			papMap.put("createDateStart",dateStart);
			papMap.put("createDateEnd",dateEnd);

			List< Map<String,Object> > iconListQuery = commonService.listDstUserVisitLogShareIcon(papMap);
			Map<String,List<String>> map =  new HashMap<String, List<String>>();
			List<String> forwardCount = new ArrayList<String>();
			List<String> dateCode = new ArrayList<String>();
			List<String> shareCount = new ArrayList<String>();

			int allShareCount = 0;
			int allForwardCount = 0;
			for(Map<String,Object>  iconMap:iconListQuery){
				BigDecimal shareCountBig = (BigDecimal) iconMap.get("shareCount");
				BigDecimal forwardCountBig = (BigDecimal) iconMap.get("forwardCount");
				allShareCount = allShareCount + Integer.valueOf(shareCountBig.toString());
				allForwardCount = allForwardCount + Integer.valueOf(forwardCountBig.toString());
				forwardCount.add(forwardCountBig.toString());
				dateCode.add(iconMap.get("dateCode").toString());
				shareCount.add(shareCountBig.toString());
			}

			map.put("forwardCount",forwardCount);
			map.put("shareCount",shareCount);
			map.put("dateCode",dateCode);
            for(Map<String,String> todayMap : todayList){
                todayMap.put("avgDate",StringUtils.isBlank(todayMap.get("avgDate"))?"10秒":DateUtil.formatDateTime(Integer.valueOf(todayMap.get("avgDate"))));
            }
            for(Map<String,String> viewMap : viewList){
                viewMap.put("avgDate",StringUtils.isBlank(viewMap.get("avgDate"))?"10秒":DateUtil.formatDateTime(Integer.valueOf(viewMap.get("avgDate"))));
            }
            for(Map<String,String> forwarMap : forwardList){
                forwarMap.put("avgDate",StringUtils.isBlank(forwarMap.get("avgDate"))?"10秒":DateUtil.formatDateTime(Integer.valueOf(forwarMap.get("avgDate"))));
            }

			result.setAttribute("todayList", todayList);
			result.setAttribute("viewList", viewList);
			result.setAttribute("forwardList", forwardList);
			result.setAttribute("iconList", map);
			result.setAttribute("allShareCount", allShareCount);
			result.setAttribute("allForwardCount", allForwardCount);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);

			logger.info("query listDstUserVisitLogShare list end .......");
		}catch(Exception e){
			log.error("query listDstUserVisitLogShare error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return result;
	}

	/***
	 * 我的访客记录列表-周报
	 * @param request
	 * @param dstUserVisitLog
	 * @param pager
	 * @return
	 */
	@RequestMapping("/listDstUserVisitLogWeekly")
	@ResponseBody
	public ResultMap listDstUserVisitLogWeekly(HttpServletRequest request, DstUserVisitLogDTO dstUserVisitLog,Pager pager){
		ResultMap result = new ResultMap();

		try{
			logger.info("query listDstUserVisitLogWeekly list begin .......");

			String openid = request.getParameter("openid");
			String date = request.getParameter("date");

            Map<String,Map<String,String>> map = DateUtil.getUpWeek(date);
            Map<String,String> upMap = new HashMap<String, String>();
            Map<String,String> upUpMap = new HashMap<String, String>();
            upMap =  map.get("up");
            upUpMap =  map.get("upUp");

            //查询
            DstUserWeeklyDTO query =  new DstUserWeeklyDTO();
            query.setUserOpenid(openid);
            query.setWeeklySDate(upMap.get("start"));
            query.setWeeklyEDate(upMap.get("end"));
            int count = dstUserWeeklyService.queryListCount(query);

            //插入 up
            if(count <= 0 ){Map<String,String> papMap = new HashMap<String, String>();
                papMap.put("openid",openid);
                papMap.put("startDate",upMap.get("start"));
                papMap.put("endDate",upMap.get("end"));
                commonService.addUserWeeklyTypeZh(papMap);
            }

            query.setWeeklySDate(upUpMap.get("start"));
            query.setWeeklyEDate(upUpMap.get("end"));
            count = dstUserWeeklyService.queryListCount(query);

            //插入 upup
            if(count <= 0 ){
                Map<String,String> papMap = new HashMap<String, String>();
                papMap.put("openid",openid);
                papMap.put("startDate",upUpMap.get("start"));
                papMap.put("endDate",upUpMap.get("end"));
                commonService.addUserWeeklyTypeZh(papMap);
            }

            //获取当前输入时间记录
            query.setWeeklySDate(upMap.get("start"));
            query.setWeeklyEDate(upMap.get("end"));
            List<DstUserWeeklyDTO> list = dstUserWeeklyService.queryList(query);

            //获取当前输入时间记录
            query.setWeeklySDate(upUpMap.get("start"));
            query.setWeeklyEDate(upUpMap.get("end"));
            List<DstUserWeeklyDTO> uplist = dstUserWeeklyService.queryList(query);

            for(DstUserWeeklyDTO bean :uplist) {
                if ("zh".equals(bean.getBusinessType())) {
                    JSONObject jsonObject = JSONObject.fromObject(bean.getBusinessData());
                    result.setAttribute("upZh", jsonObject);
                }
            }

            for(DstUserWeeklyDTO bean :list){
                if("zh".equals(bean.getBusinessType())){
                    JSONObject  jsonObject = JSONObject.fromObject( bean.getBusinessData());
                    result.setAttribute("zh",jsonObject);
                }
                if("view".equals(bean.getBusinessType())){
                    Map<String,Object> viewMap = new HashMap<String,Object>();
                    JSONObject  jsonObject = JSONObject.fromObject( bean.getBusinessData());
                    String viewtop  = jsonObject.getString("viewtop");
                    String forwardtop  = jsonObject.getString("forwardtop");
                    viewMap.put("viewtop", viewtop.split(","));
                    viewMap.put("forwardtop", forwardtop.split(","));
                    result.setAttribute("view",viewMap);
                }
                if("wz".equals(bean.getBusinessType())){

                    List<Map<String,Object>> viewMapList = new ArrayList<Map<String, Object>>();
                    Map<String,Object> wz = new HashMap<String,Object>();
                    JSONObject  jsonObject = JSONObject.fromObject( bean.getBusinessData());
                    String title  = jsonObject.getString("title");
                    String viewCount  = jsonObject.getString("viewCount");
                    String allCount  = jsonObject.getString("allCount");
                    String[] titles = title.split("sfa@sfa");
                    String[] viewCounts = viewCount.split(",");
                    if(titles.length>5){
                    	String[] copy = new String[6];
                    	for (int i = 0; i < copy.length; i++) {
                    		copy[i]=titles[i];
						}
                    	copy[5]="其他";
                    	wz.put("title",copy);
                    }else{
                    	wz.put("title", titles);
                    }

                    int countView = 0;
                    if(org.apache.commons.lang.StringUtils.isNotBlank(viewCount)) {
                        for (int j = 0; j < viewCounts.length; j++) {
                        	 Map<String, Object> viewMap = new HashMap<String, Object>();
                        	 if(j>4){
                             	viewMap.put("name", "其他");
                             	viewMap.put("value", 100-countView);
                             	viewMapList.add(viewMap);
                             	break;
                             }
                            Float viewCountInt = Float.valueOf(viewCounts[j]);
                            int value = Math.round((viewCountInt / Float.valueOf(allCount)) * 100);
                            viewMap.put("name", titles[j]);
                            if (j == viewCounts.length - 1) {
                                viewMap.put("value", 100 - countView);
                            } else {
                                viewMap.put("value", value);
                            }
                            countView = countView + value;
                            viewMapList.add(viewMap);
                        }
                    }
                    wz.put("viewCount", viewMapList);
                    wz.put("allCount", allCount);
                    result.setAttribute("wz",wz);
                }
            }
            if(result.getAttribute("zh") instanceof  JSONObject && result.getAttribute("upZh") instanceof JSONObject){
                JSONObject zh =  (JSONObject)result.getAttribute("zh");
                JSONObject upZh =  (JSONObject)result.getAttribute("upZh");
                result.setAttribute("upZh",null);
                zh.put("allCountCompare",compareValue(zh.getInt("allCount"), upZh.getInt("allCount")));
                zh.put("shareArticleCountCompare",compareValue(zh.getInt("shareArticleCount"), upZh.getInt("shareArticleCount")));
                zh.put("forwardArticleCountCompare",compareValue(zh.getInt("forwardArticleCount"), upZh.getInt("forwardArticleCount")));
                zh.put("visitPeopleCountCompare",compareValue(zh.getInt("visitPeopleCount"), upZh.getInt("visitPeopleCount")));

                zh.put("conversionRate",compareValueRate(zh.getInt("forwardPeopleCount"), zh.getInt("viewPeopleCount")));
                zh.put("conversionRateCompare",compareValue(zh.getInt("conversionRate"),compareValueRate(upZh.getInt("forwardPeopleCount"), upZh.getInt("viewPeopleCount"))));

                zh.put("forwardConversionRate",compareValueRate(zh.getInt("forwardArticlePeople"), zh.getInt("viewPeopleCount")));
                zh.put("forwardViewConversionRate",compareValueRate(zh.getInt("forwardPeopleCount"), zh.getInt("visitPeopleCount")));
                result.setAttribute("zh",zh);
            }


			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);

			logger.info("query listDstUserVisitLogWeekly list end .......");
		}catch(Exception e){
			log.error("query listDstUserVisitLogWeekly error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return result;
	}

    /***
     * 我的访客记录列表-周报-参数自然周
     * @param request
     * @param dstUserVisitLog
     * @param pager
     * @return
     */
    @RequestMapping("/queryNaturalWeek")
    @ResponseBody
    public ResultMap queryNaturalWeek(HttpServletRequest request, DstUserVisitLogDTO dstUserVisitLog,Pager pager){
        ResultMap result = new ResultMap();

        try{
            logger.info("query listDstUserVisitLogWeekly list begin .......");

            String openid = request.getParameter("openid");
            //如果用户不存在  直接返回
            DstUserInfoDTO dstUserInfo = new DstUserInfoDTO();
            dstUserInfo.setUserWechatOpenid(openid);
            dstUserInfo.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
            DstUserInfoDTO userinfo = dstUserInfoService.queryListGetFirst(dstUserInfo);
            if(userinfo.getId()==null){
                logger.error("openid is not existent :"+openid);
                result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
                result.setStatus(ResultMap.STATUS.FAILE);
                return result;
            }

            result.setAttribute("dateList",DateUtil.queryNaturalWeek(userinfo.getCreateDate()));
            result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
            result.setStatus(ResultMap.STATUS.SUCCESS);

            logger.info("query listDstUserVisitLogWeekly list end .......");
        }catch(Exception e){
            log.error("query listDstUserVisitLogWeekly error!",e);
            result.setStatus(ResultMap.STATUS.ERROR);
            result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
        }

        return result;
    }
	private int compareValue (int data,int upData){
		if(data == 0 && upData == 0){
			return 0;
		}
		if(data != 0 && upData == 0){
			return 100;
		}
		if(data == 0 && upData != 0) {
			return -100;
		}
		return (data*100/upData-100);

    }
	private int compareValueRate (int data,int data1){
		if(data == 0 && data1 == 0){
			return 0;
		}
		if(data != 0 && data1 == 0){
			return 100;
		}
		if(data == 0 && data1 != 0) {
			return 0;
		}
		return (data*100/data1);

	}

	/***
	 * 日常统计
	 * @param request
	 * @return
	 */
	@RequestMapping("/dstUserVisitLog")
	@ResponseBody
	public ResultMap dstUserVisitLog(HttpServletRequest request){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("dstUserVisitLog begin .......");
			 String openid=request.getParameter("openid");
			//参数  默认
			if(StringUtils.isBlank(openid)){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			DstUserVisitLogDTO dstUserVisitLog =new DstUserVisitLogDTO();
			dstUserVisitLog.setUserOpenid(openid);
			//统计
			DstUserCountInfoVO visitDateLog = commonService.visitDateLog(openid);
			result.setAttribute("visitDateLog", visitDateLog);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			logger.info("dstUserVisitLog end .......");
		}catch(Exception e){
			log.error("dstUserVisitLog error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	/***
	 * 用户访问详情 日志流水
	 * @param request
	 * @param dstUserVisitLog
	 * @return
	 */
	@RequestMapping("/addDstUserVisitLog")
	@ResponseBody
	public ResultMap add(HttpServletRequest request, DstUserVisitLogDTO dstUserVisitLog){
		ResultMap result = new ResultMap();
		try{
			logger.info("add dstUserVisitLog  begin .......");
			 String openid=request.getParameter("openid");
			String shareCode=request.getParameter("shareCode");
			//参数  默认
			if(StringUtils.isBlank(openid)||dstUserVisitLog.getVisitUserArticleCode()==null){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			//自己访问自己  
			if(StringUtils.isBlank(dstUserVisitLog.getUserOpenid())||openid.equals(dstUserVisitLog.getUserOpenid())){
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setStatus(ResultMap.STATUS.SUCCESS);
				return result;
			}
			
			DstUserArticleDTO dstUserArticle=new DstUserArticleDTO();
			dstUserArticle.setUserOpenid(dstUserVisitLog.getUserOpenid());
			dstUserArticle.setDstArticleCode(dstUserVisitLog.getVisitUserArticleCode());
			dstUserArticle.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
			DstUserArticleDTO userArticle = dstUserArticleService.queryListGetFirst(dstUserArticle);
			//文章不存在
			if(userArticle.getId()==null){
				logger.error("article is not getDstArticleCode existent articleId:"+userArticle.getDstArticleCode()+",openid="+dstUserVisitLog.getUserOpenid());
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setStatus(ResultMap.STATUS.SUCCESS);
				return result;
			}
			DstArticleDTO dstArticle=new DstArticleDTO();
			dstArticle.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
			dstArticle.setDstArticleCode(userArticle.getDstArticleCode());
			DstArticleDTO article = dstArticleService.queryListGetFirst(dstArticle);
			//文章不存在
			if(article.getId()==null){
				logger.error("article is not getDstArticleCode existent :"+userArticle.getDstArticleCode());
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setStatus(ResultMap.STATUS.SUCCESS);
				return result;
			}
			
			//文章所属人用户信息
			DstUserInfoDTO uifd = new DstUserInfoDTO();
			uifd.setUserWechatOpenid(dstUserVisitLog.getUserOpenid());
			uifd.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
			DstUserInfoDTO ud = dstUserInfoService.queryListGetFirst(uifd);
			if(ud.getId()==null){
				logger.error("getUserOpenid is not existent :"+openid);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setStatus(ResultMap.STATUS.SUCCESS);
				return result;
			}
			//如果用户不存在  直接返回
			DstUserInfoDTO dstUserInfo = new DstUserInfoDTO();
			dstUserInfo.setUserWechatOpenid(openid);
			dstUserInfo.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
			DstUserInfoDTO userinfo = dstUserInfoService.queryListGetFirst(dstUserInfo);
			if(userinfo.getId()==null){
				logger.error("openid is not existent :"+openid);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setStatus(ResultMap.STATUS.SUCCESS);
				return result;
			}
			synchronized (obj) {
				
				DstUserVisitLogDTO query=new DstUserVisitLogDTO();
				query.setVisitUserArticleCode(dstUserVisitLog.getVisitUserArticleCode());
				query.setVisitUserOpenid(openid);
				query.setUserOpenid(userArticle.getUserOpenid());
				DstUserVisitLogDTO dtoVisit = dstUserVisitLogService.queryListGetFirst(query);
				//最新访问一次在30秒内直接返回
				if(dtoVisit.getUpdateDate()!=null&&DateUtil.addSecond(dtoVisit.getUpdateDate(), 30).after(new Date())){
					result.setAttribute("id",dtoVisit.getId());
					result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
					result.setStatus(ResultMap.STATUS.SUCCESS);
					return result;
				}
				// 增加文章访问的记录 
				DstArticleDTO d=new DstArticleDTO();
				d.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
				d.setDstArticleCode(userArticle.getDstArticleCode());
				d.setViewCount(1);
				DTOdateSetUtil.setUpdateInfo(d);
				commonService.addVisitArticleLog(d);
				
				//如果分享人就是文章所属人  
				if(dstUserVisitLog.getUserOpenid().equals(dstUserVisitLog.getShareUserOpenid()))
					dstUserVisitLog.setShareUserOpenid("");
				dstUserVisitLog.setUserOpenid(userArticle.getUserOpenid());
				dstUserVisitLog.setVisitUserNickname(userinfo.getUserName());
				dstUserVisitLog.setVisitUserHeadImageurl(userinfo.getUserWechatImage());
				dstUserVisitLog.setVisitUserOpenid(openid);
				dstUserVisitLog.setVisitUserDate(DateUtil.getDate("yyyy-MM-dd"));
				//记录访问信息   默认停留1秒
				dstUserVisitLog.setVisitStayDate(1);
				DTOdateSetUtil.setCreateInfo(dstUserVisitLog);
				DTOdateSetUtil.setUpdateInfo(dstUserVisitLog);


				//根据分享code，获取分享记录,得到visitId,获取visit上级的全链路
				if(StringUtils.isNotBlank(shareCode)){
					DstArticleShareLogDTO dstArticleShareLog = new DstArticleShareLogDTO();
					dstArticleShareLog.setShareCode(shareCode);
					dstArticleShareLog = dstArticleShareLogService.queryListGetFirst(dstArticleShareLog);

					if(dstArticleShareLog.getId() != null){
						dstUserVisitLog.setShareId(dstArticleShareLog.getId());

						if(dstArticleShareLog.getVisitId() != null){
							DstUserVisitLogDTO visitPath = dstUserVisitLogService.loadById(dstArticleShareLog.getVisitId());
							if(visitPath != null){

                                //openId 全链路
								String userOpenidPath =StringUtils.isBlank(visitPath.getShareUserOpenidPath())?visitPath.getUserOpenid():visitPath.getShareUserOpenidPath();
                                dstUserVisitLog.setShareUserOpenidPath(userOpenidPath+","+dstUserVisitLog.getShareUserOpenid());

                                //openName headImg 全链路
                                String userName = StringUtils.EMPTY;
                                String userHeadImg = StringUtils.EMPTY;
                                if(StringUtils.isBlank(visitPath.getShareUserNamePath())){
                                    //文章所属人用户信息
                                    DstUserInfoDTO userPath = new DstUserInfoDTO();
                                    userPath.setUserWechatOpenid(visitPath.getUserOpenid());
                                    userPath.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
                                    userPath = dstUserInfoService.queryListGetFirst(userPath);
                                    userName =StringUtils.isBlank( userPath.getUserName())?"":userPath.getUserName();
                                    userHeadImg = StringUtils.isBlank( userPath.getUserWechatImage())?"":userPath.getUserWechatImage();
                                }

                                String userNamePath = StringUtils.isBlank(visitPath.getShareUserNamePath())?userName:visitPath.getShareUserNamePath();
                                String userHeadImgPath = StringUtils.isBlank(visitPath.getShareUserHeadImageurlPath())?userHeadImg:visitPath.getShareUserHeadImageurlPath();
                                if(StringUtils.isNotBlank(dstUserVisitLog.getShareUserOpenid())){
                                    //文章所属人用户信息
                                    DstUserInfoDTO sharePath = new DstUserInfoDTO();
                                    sharePath.setUserWechatOpenid(dstUserVisitLog.getShareUserOpenid());
                                    sharePath.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
                                    sharePath = dstUserInfoService.queryListGetFirst(sharePath);
                                    dstUserVisitLog.setShareUserNamePath(userNamePath+"@sfa@"+sharePath.getUserName());
                                    dstUserVisitLog.setShareUserHeadImageurlPath(userHeadImgPath+"@sfa@"+sharePath.getUserWechatImage());
                                }
							}
						}
					}
				}

				int id = dstUserVisitLogService.insert(dstUserVisitLog);

				//积分规则
				dstIntegralRuleService.execute(userArticle.getUserOpenid(),"visitArticlePeople");

				result.setAttribute("id",id);
				
			}
			//TODO 判断设置 访问文章页面 及时发送 发送机制    
			DstUserSettingDTO userSetting = new DstUserSettingDTO();
			userSetting.setUserOpenid(userArticle.getUserOpenid());
			userSetting.setDeleteTag(CommonConstantUtil.CommonStatus.DELETE_TAG_NORMAL);
			DstUserSettingDTO usetting = dstUserSettingService.queryListGetFirst(userSetting);
			if (usetting.getId() == null 
					|| UserInfoStatus.MESSAGE_SEND_SETTING_1.equals(usetting
							.getMessageSendSetting())) {
				//夜间是否提醒
				int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
				logger.info("MESSAGE_SEND_SETTING_1 = is  send visit info,date:"+hour+",openid is :"+openid);
				if( (hour>=23 || hour<=6) && UserInfoStatus.MESSAGE_SEND_Night_2.equals(usetting.getMessageSendNight())){
					//夜间勿扰
					logger.info("MESSAGE_SEND_Night_2 = is not send visit info");
				}else{
					if("1".equals(ud.getFlagConcern())){
						
						//查询备注客户名称
						DstUserClientViewDTO dstUserClientView=new DstUserClientViewDTO();
						dstUserClientView.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
						dstUserClientView.setUserClientOpenid(userinfo.getUserWechatOpenid());
						dstUserClientView.setUserOpenid(userArticle.getUserOpenid());
						DstUserClientViewDTO view = dstUserClientViewService.queryListGetFirst(dstUserClientView);
						if(StringUtils.isNotBlank(view.getUserClientName())){
							userinfo.setUserName(userinfo.getUserName()+"("+view.getUserClientName()+")");
						}
						String articleUrl=MessageFormat.format(CommonStatus.articleDetailPage, dstUserVisitLog.getVisitUserArticleCode(),dstUserVisitLog.getUserOpenid());
						String text = "%s 阅读了您的文章\n\n<a href='%s'>%s</a>\n\n点击下方<a href='%s'>【访问数据】</a>查看\n推送频率设置可以<a href='%s'>点击这里</a>";
						String title = StringUtils.isBlank(userArticle.getTitle())?article.getTitle():userArticle.getTitle();
						text=String.format(text,userinfo.getUserName(),articleUrl,title, CommonStatus.visitPage,CommonStatus.noticeSetting);
						boolean sendKefuMessage=false;
						try {
							WxMpKefuMessage message = WxMpKefuMessage.TEXT()
									.toUser(userArticle.getUserOpenid())
									.content(text)
									.build();
							sendKefuMessage = weixinJincsServiceImpl.sendKefuMessage(message);
						} catch (Exception e) {
							logger.error("send error ");
						}
						logger.info("openid:"+userArticle.getUserOpenid()+",send "+userinfo.getUserName()+" vist!!!:"+sendKefuMessage);
					}else{
						logger.info("openid:"+userArticle.getUserOpenid()+",send "+userinfo.getUserName()+" vist!!!:response out of time limit or subscription is canceled");
						
					}
				}
			}
			
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("add dstUserVisitLog list end .......");
		}catch(Exception e){
			log.error("add dstUserVisitLog error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	/***
	 * 轮询记录访问时长
	 * @param request
	 * @param dstUserVisitLog
	 * @return
	 */
	@RequestMapping("/visitLogStayDate")
	@ResponseBody
	public ResultMap visitLogStayDate(HttpServletRequest request, DstUserVisitLogDTO dstUserVisitLog){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("add visitLogStayDate begin .......");
			Integer id = dstUserVisitLog.getId();
			String openid=request.getParameter("openid");
			if(id==null||StringUtils.isBlank(openid)){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			DstUserVisitLogDTO dto = dstUserVisitLogService.loadById(id);
			
			// 本人不返回
			if(openid.equals(dto.getUserOpenid())){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			
			//计算停留时间 获取当前时间-创建时间
			long timeCount = ((new Date(System.currentTimeMillis())).getTime()-dto.getCreateDate().getTime())/1000;
			logger.info("add visitLogStayDate  .......timeCount:"+timeCount);
			dto.setVisitStayDate(timeCount>1?(int)timeCount:1);
			DTOdateSetUtil.setUpdateInfo(dto);
			dstUserVisitLogService.update(dto);
			
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("add visitLogStayDate  end .......");
		}catch(Exception e){
			log.error("add visitLogStayDate error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	
	
	/***
	 * 我的访客记录列表   没有会员访问记录
	 * @param request
	 * @return
	 */
	@RequestMapping("/noMemberUserVisitLog")
	@ResponseBody
	public ResultMap noMemberUserVisitLog(HttpServletRequest request){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("noMemberUserVisitLog begin .......");
			
			 String openid=request.getParameter("openid");
			//参数  默认
			if(StringUtils.isBlank(openid)){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
            //参数  默认
            if(StringUtils.isBlank(openid)){
                result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
                result.setStatus(ResultMap.STATUS.FAILE);
                return result;
            }
            DstUserVisitLogDTO dstUserVisitLog=new DstUserVisitLogDTO();
			dstUserVisitLog.setUserOpenid(openid);
			dstUserVisitLog.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
			dstUserVisitLog.setBegin(0);
			dstUserVisitLog.setPageSize(3);
			List<DstUserVisitLogVO> dstUserVisitLogList = commonService.dstUserVisitLogList(dstUserVisitLog);

            //统计-总流量
            DstUserCountInfoVO visitDateLog = commonService.visitDateLog(openid);
            result.setAttribute("allCount", visitDateLog.getAllVist());
            result.setAttribute("todayVisit", visitDateLog.getTodayVisit());
            result.setAttribute("list",dstUserVisitLogList);
            
            result.setAttribute("flagMember",false);
            DstMemberInfoDTO dstMemberInfo=new DstMemberInfoDTO();
			dstMemberInfo.setUserOpenid(openid);
			try {
				DstMemberInfoDTO dto = dstMemberInfoService.queryListGetFirst(dstMemberInfo);
				if(dto.getId()!=null&&dto.getMemberEndDate()!=null&&new Date().before(dto.getMemberEndDate())){
					result.setAttribute("flagMember",true);
				}
			}catch(Exception e){
				logger.info("dstMemberInfoService query error",e);
			}
            
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("noMemberUserVisitLog end .......");
		}catch(Exception e){
			log.error("noMemberUserVisitLog error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
}
